<?php

namespace app\api\controller\spike;

use app\api\controller\AuthController;
use app\api\service\OrderService;
use app\api\service\PaymentService;
use app\api\service\SpikeOrderService;
use think\exception\ValidateException;
use think\facade\Db;

class OrderController extends AuthController
{
    /**
     * 生成订单
     * */
    public function save()
    {
        $param = $this->request->param();

        try{
            validate('SpikeOrderValidate')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0,'msg' => $e->getError()]);
        }

        $logistics_mode = empty($param['logistics_mode']) ? 1 : 2;
        $param['logistics_mode'] = $logistics_mode;

        if ($param['logistics_mode'] != 1) {
            if (empty($param['pick_point_id'])) {
                return json(['code' => 0, '请选择自提点']);
            }
            $is_pick_point = Db::name('pick_point')->where(['store_id' => $param['store_id'], 'status' => 1, 'id' => $param['pick_point_id'], 'delete_time' => 0])->find();
            if (empty($is_pick_point)) {
                return json(['code' => 0, '自提点不存在']);
            }
        }

        $end_time = SpikeOrderService::getSpikeSessionTime($param['spike_session_id']);
        // echo $end_time;exit;
        if ($end_time+3600<time()){
            return json(['code' => 0,'msg' => '秒杀已结束!']);
        }

        if (!empty($param['spike_goods_id'])){
            $goods = SpikeOrderService::findSingleSpikeGoods($param['spike_goods_id']);
        }

        if (!empty($param['sku_id'])){
            $goods = SpikeOrderService::findManySpikeGoods($param['sku_id']);
        }

        if (empty($goods)){
            return json(['code' => 0,'msg' => '商品已下架']);
        }


        $param['buy_num'] = isset($param['buy_num']) ? $param['buy_num'] : 1;

        if ($goods['spike_stock']< $param['buy_num']){
            return json(['code' => 0,'msg' => '库存不足']);
        }

        $user_id = $this->request->user['user_id'];

        if ($goods['spec_type'] ==1){
            $goods['image'] = $goods['main_image'];
        }

        if ($goods['spec_type'] ==2){
            $goods['image'] = !empty($data['image']) ? $data['image'] : $goods['main_image'];
        }

        $real_amount = number_format($goods['spike_price']*$param['buy_num'],2);

        $order_no = PaymentService::generateOrderNum();
        $out_trade_no = PaymentService::generateOrderNum(10);



        /**
         * 保存订单信息
         * */
        $data = array_merge($param,$goods,[
            'user_id' => $user_id,
            'order_type' => 2,
            'real_amount' => $real_amount,
            'order_no' => $order_no,
            'out_trade_no' => $out_trade_no,
            'market_price' => $goods['sell_price'],
            'sell_price' => $goods['spike_price'],
        ]);

        $result = OrderService::saveOrder($data, false, true);


        if ($result === false){
            return  json(['code' =>0, 'msg'=> '下单失败!']);
        }


        $config = PaymentService::findPaymentConfig($param['store_id'],$param['payment_type']);

        if (empty($config)){
            return  json(['code' =>0, 'msg' =>'支付异常!']);
        }
        $payment_data = [
            'config' => $config,
            'trade_method' => $data['payment_type'],
            'out_trade_no' => $out_trade_no,
            'real_amount' => $real_amount,
        ];

        if ($data['payment_type'] == 1){
            $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/order/trade/wx/notify';
        }

        if ($data['payment_type'] == 2){
            $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/order/trade/ali/notify';
        }


        $prepay_info = PaymentService::createOrder($payment_data);

        if (!empty($prepay_info)){
            return json([
                'code' =>1,
                'data' => [
                    'out_trade_no' => $out_trade_no,
                    'prepay_info' => $prepay_info
                ],
                'msg' => '下单成功!'
            ]);
        }

        return  json(['code' =>0, 'msg' => '下单失败!']);

    }
}